//
//  CourseListViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/23.
//

#import "CourseListViewController.h"
#import "CourseListCell.h"
#import "CourseListManager.h"
#import "CourseListModel.h"
#import "ResetCourseManager.h"
#import "MemorizeWordsViewController.h"
#import "CourseDetialViewController.h"
#import "JPNavigationController.h"

@interface CourseListViewController ()<UITableViewDelegate,UITableViewDataSource,JPAPIManagerCallBackDelegate,CourseListCellDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)CourseListManager *listManager;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)ResetCourseManager *resetCourseManager;
@property(nonatomic,assign)NSInteger sel_index;
@property(nonatomic,assign)NSInteger swipeIndex;

@end

@implementation CourseListViewController

-(CourseListManager *)listManager{
    if(!_listManager){
        _listManager = [[CourseListManager alloc]init];
        _listManager.delegate = self;
    }
    return _listManager;
}

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(ResetCourseManager *)resetCourseManager{
    if(!_resetCourseManager){
        _resetCourseManager = [[ResetCourseManager alloc]init];
        _resetCourseManager.delegate = self;
    }
    return _resetCourseManager;
}


-(void)viewDidLoad{
    [super viewDidLoad];
    self.swipeIndex = -1;
    [self createUI];
    [self loadData];
    
}


-(void)loadData{
    self.listManager.bookId = self.bookModel.bookId;
    [self.listManager loadData];
}

-(void)createUI{
        
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    
    [self.customNavigationBar setTitle:[NSString stringWithFormat:@"%@ (%@)",self.bookModel.name,self.bookModel.volumeName]];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(16,kYM_NAVIGATIONBAR_HEIGHT, self.currentAvailableWidth-32,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 80;
    self.tableView.backgroundColor = KbgColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:NSClassFromString(@"CourseListCell") forCellReuseIdentifier:@"CourseListCell"];
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth, 81)];
    footerView.backgroundColor = KbgColor;
    self.tableView.tableFooterView = footerView;
    
    __weak typeof(self)self_weak_ = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self_weak_.dataArr removeAllObjects];
        [self_weak_ loadData];
    }];
    
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         // 获取当前可用宽度并更新布局
         self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
         self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
         self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
         self.tableView.frame = CGRectMake(16,kYM_NAVIGATIONBAR_HEIGHT, self.currentAvailableWidth-32,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
         [self.tableView reloadData];
         UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth, 81)];
         footerView.backgroundColor = KbgColor;
         self.tableView.tableFooterView = footerView;
            
        });
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CourseListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CourseListCell"];
    if(indexPath.section < self.dataArr.count){
        cell.currentAvailableWidth = self.currentAvailableWidth;
        if(isIPAD){
            [cell refreshWidth];
        }
        cell.section = indexPath.section;
        cell.delegate = self;
        CourseListModel *model = self.dataArr[indexPath.section];
        cell.model = model;
        if(self.swipeIndex != -1){
            if(indexPath.section == self.swipeIndex){
                [cell refreshWithIsSwipe:YES andDynamic:NO];
            }else{
                [cell refreshWithIsSwipe:NO andDynamic:NO];
            }
        }
        
        // 添加滑动手势识别器
        UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
            swipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
        [cell addGestureRecognizer:swipeGesture];
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth, 12)];
    headView.backgroundColor = KbgColor;
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 12;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0,0, self.currentAvailableWidth, 0.00001)];
    footerView.backgroundColor = KbgColor;
    return footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.00001;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if((self.swipeIndex != -1)&&(indexPath.section == self.swipeIndex)){
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:self.swipeIndex];
        CourseListCell *cell0 = [self.tableView cellForRowAtIndexPath:indexPath];
        [cell0 refreshWithIsSwipe:NO andDynamic:YES];
    }else{
        CourseDetialViewController *vc = [[CourseDetialViewController alloc]init];
        vc.bookModel = self.bookModel;
        if(indexPath.section < self.dataArr.count){
            CourseListModel *model = self.dataArr[indexPath.section];
            vc.courseModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    
}

#pragma mark - 侧滑
- (void)handleSwipeGesture:(UISwipeGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateEnded){
        CourseListCell *cell = (CourseListCell *)gesture.view;
        if(self.swipeIndex != -1){
            //复原原来的
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:self.swipeIndex];
            CourseListCell *cell0 = [self.tableView cellForRowAtIndexPath:indexPath];
            [cell0 refreshWithIsSwipe:NO andDynamic:NO];
        }
        [cell refreshWithIsSwipe:YES andDynamic:YES];
        self.swipeIndex = cell.section;
    }
    
}

#pragma mark - 重置
-(void)resetTap:(CourseListCell *)cell{
    self.swipeIndex = -1;
    NSInteger section = cell.section;
    if(section < self.dataArr.count){
        self.sel_index = section;
        CourseListModel *model = self.dataArr[section];
        self.resetCourseManager.ucId = model.ucId;
        [self.resetCourseManager loadData];
    }
}

#pragma mark - 开始背词
-(void)beginTap:(CourseListCell *)cell{
    
    MemorizeWordsViewController *vc = [[MemorizeWordsViewController alloc] init];
    vc.courseModel = cell.model;
    JPNavigationController *nav = [[JPNavigationController alloc]initWithRootViewController:vc];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:nav animated:YES completion:nil];
    __weak typeof(self)weakSelf = self;
    [vc setRefrehBlock:^{
        //发个通知刷新首页
        [[NSNotificationCenter defaultCenter]postNotificationName:@"WordProgessUpdate" object:nil];
        weakSelf.swipeIndex = -1;
        [weakSelf.dataArr removeAllObjects];
        [weakSelf loadData];
    }];
    
}


#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.listManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [CourseListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.dataArr = [NSMutableArray arrayWithArray:arr];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    }
    
    if([manager isEqual:self.resetCourseManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        if(self.sel_index < self.dataArr.count){
            CourseListModel *model = self.dataArr[self.sel_index];
            model.percent = @"0";
            model.finish = @"0";
            [self.dataArr replaceObjectAtIndex:self.sel_index withObject:model];
        }
        [self.tableView reloadData];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"WordProgessUpdate" object:nil];
    }
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    [self.tableView.mj_header endRefreshing];
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


@end
